//
//  YKNetHelp.m
//  BiaoPny
//
//  Created by QFYK on 2017/5/12.
//  Copyright © 2017年 BiaoPu. All rights reserved.
//

#import "YKNetHelp.h"
#import "AFHTTPSessionManager.h"

/**
 *  AFNetWorking的最新版本的使用方法
 */
static YKNetHelp *_shareManager = nil;
@implementation YKNetHelp

+ (instancetype)shareManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        // AFHTTPSessionManager 单例对象，可以在程序短时间内发起多个请求时，降低系统开销
        _shareManager = [[super allocWithZone:NULL] initWithBaseURL:[NSURL URLWithString:@""]];
        // 设置请求内容的序列化方式
        _shareManager.requestSerializer = [AFHTTPRequestSerializer serializer];
        _shareManager.requestSerializer.timeoutInterval = 10;
        // 设置服务器数据的序列化方式
        _shareManager.responseSerializer = [AFHTTPResponseSerializer serializer];
        // 设置可接受的服务器数据的格式
        _shareManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/xml", @"text/plain", nil];
        
        // 当手机处于无网络状态时，必须给出提示，不然会被拒绝。
        [self isReachToWeb];
    });
    return _shareManager;
}

+ ( void)isReachToWeb {
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusUnknown: {
                break;
            }
            case AFNetworkReachabilityStatusNotReachable: {
//                               [[UIViewController currentViewController] showSuccessHUDWithStr:@"网络好像有点问题"];
//                [[UIViewController currentViewController] showTextHUDWithStr:@"网络好像有点问题"];
                
                
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"" message:@"网络好像有点问题" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                [alert show];
                
                
                NSLog(@"无网络");
                break;
            }
            case AFNetworkReachabilityStatusReachableViaWWAN: {
                break;
            }
            case AFNetworkReachabilityStatusReachableViaWiFi: {
                break;
            }
        }
    }];
    
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    
}

// 封装 Post 请求，成功和失败在一个 block 里面处理
+ (void)postWithPath:(NSString *)path andParams:(NSDictionary *)params andComplete:(void (^)(BOOL success, id result))complete {
    
    //每次请求之前从本地获取cookies
    NSArray *arcCookies = [NSKeyedUnarchiver unarchiveObjectWithData: [[NSUserDefaults standardUserDefaults] objectForKey: @"sessionCookies"]];
    NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    
    for (NSHTTPCookie *cookie in arcCookies){
        [cookieStorage setCookie: cookie];
    }
    
    [[self shareManager] POST:path parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"请求的进度");
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSObject *data = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        
        //每次请求成功，保存cookies
        NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
        NSData *cookiesData = [NSKeyedArchiver archivedDataWithRootObject: cookies];
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject: cookiesData forKey: @"sessionCookies"];
        [defaults synchronize];
        
        complete(YES,data);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self isReachToWeb];
        complete(0, error);
    }];
}

// 封装 Get 请求，成功和失败分开处理
+ (void)getDataWithPath:(NSString *)path andParams:(NSDictionary *)params andComplete:(void (^)(BOOL success, id result))complete {
    
    //每次请求之前从本地获取cookies
    NSArray *arcCookies = [NSKeyedUnarchiver unarchiveObjectWithData: [[NSUserDefaults standardUserDefaults] objectForKey: @"sessionCookies"]];
    NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    
    for (NSHTTPCookie *cookie in arcCookies){
        [cookieStorage setCookie: cookie];
    }
    [[self shareManager] GET:path parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        NSLog(@"请求的过程");
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSObject *data = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        //每次请求成功，保存cookies
        NSData *cookiesData = [NSKeyedArchiver archivedDataWithRootObject: [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]];
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject: cookiesData forKey: @"sessionCookies"];
        [defaults synchronize];
        
        complete(YES,data);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self isReachToWeb];
        complete(NO,error.localizedDescription);
    }];
}

+ (void)deleteDataWithPath:(NSString *)path andParams:(NSDictionary *)params andComplete:(void (^)(BOOL success, id result))complete
{
    //每次请求之前从本地获取cookies
    NSArray *arcCookies = [NSKeyedUnarchiver unarchiveObjectWithData: [[NSUserDefaults standardUserDefaults] objectForKey: @"sessionCookies"]];
    NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    
    for (NSHTTPCookie *cookie in arcCookies){
        [cookieStorage setCookie: cookie];
    }
    
    [[self shareManager] DELETE:path parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSObject *data = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        //每次请求成功，保存cookies
        NSData *cookiesData = [NSKeyedArchiver archivedDataWithRootObject: [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]];
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject: cookiesData forKey: @"sessionCookies"];
        [defaults synchronize];
        
        complete(YES,data);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self isReachToWeb];
        complete(NO,error.localizedDescription);
    }];
}

//+ (void)getPictureWithImage:(UIImageView *)imageView andURLString:(NSString *)url
//{
//    NSURL *urlstr = [NSURL URLWithString:url];
////    [imageView sd_setImageWithURL:urlstr placeholderImage:[UIImage imageNamed:@"120"]];
//}
//
//+ (void)getPictureWithImageBigPlachoderPic:(UIImageView *)imageView andURLString:(NSString *)url
//{
//    NSURL *urlstr = [NSURL URLWithString:url];
////    [imageView sd_setImageWithURL:urlstr placeholderImage:[UIImage imageNamed:@"130"]];
//}
//
//#pragma mark - 王豫凯增加2016年04月22日16:11:16   --------> 可拿到的数据图片
//+ (void)getPictureWithImage:(UIImageView *)imageView andURLString:(NSString *)url andCompleteBackImage:(void (^)(UIImage *backimage))backimage
//{
//    NSURL *urlstr = [NSURL URLWithString:url];
//    //    [imageView sd_setImageWithURL:urlstr completed:^(UIImage *image, NSError *error, EMSDImageCacheType cacheType, NSURL *imageURL) {
//    //         backimage(image);
//    //    }];
////    [imageView sd_setImageWithURL:urlstr placeholderImage:[UIImage imageNamed:@"120"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
//        backimage(image);
//    }];
//}


@end
